<template>
  <div class="container">
    <!-- 左侧 - TODO列表 -->
    <div class="column left">
      <div class="toolbar">
        <input
          v-model="newTodo"
          @keyup.enter="addTodo"
          placeholder="添加新任务"
        />
        <el-button type="primary" @click="addTodo">添加</el-button>
      </div>
      <el-tabs class="filters" v-model="filter" @tab-change="handleTabChange">
        <el-tab-pane label="全部" name="all"></el-tab-pane>
        <el-tab-pane label="未完成" name="active"></el-tab-pane>
        <el-tab-pane label="已完成" name="completed"></el-tab-pane>
      </el-tabs>
      <div class="todo-list-container">
        <draggable
          v-model="filteredTodos"
          tag="ul"
          class="todo-list"
          v-if="filteredTodos.length"
          @end="onDragEnd"
        >
          <!-- Use the default slot correctly -->
          <template #item="{ element: todo }">
            <li
              :key="todo.id"
              :class="{ completed: todo.completed, editing: todo.editing }"
              @click="selectTodo(todo)"
            >
              <label>
                <input type="checkbox" v-model="todo.completed" />
                <span
                  :contenteditable="todo.editing"
                  @blur="saveEdit(todo)"
                  autofocus
                  >{{ todo.text }}</span
                >
              </label>
              <div class="actions">
                <el-button type="sencordary" @click="toggleComplete(todo)">
                  {{ todo.completed ? "撤销" : "完成" }}
                </el-button>
                <el-button type="sencordary" @click="startEdit(todo)"
                  >编辑</el-button
                >
                <el-button type="sencordary" @click="removeTodo(todo.id)"
                  >删除</el-button
                >
              </div>
            </li>
          </template>
        </draggable>
        <el-empty description="暂无任务" v-else></el-empty>
      </div>
    </div>

    <!-- 中间 - 任务详情 -->
    <div class="column middle">
      <h2>任务详情</h2>
      <div v-if="selectedTodo">
        <h3>{{ selectedTodo.text }}</h3>
        <p>状态：{{ selectedTodo.completed ? "已完成" : "未完成" }}</p>
        <p>创建时间：{{ formattedCreateDate }}</p>
        <p v-if="selectedTodo.deadline">截止时间：{{ formattedDeadline }}</p>
        <p>优先级：{{ selectedTodo.priority || "未设置" }}</p>
        <div v-if="selectedTodo.remark">
          <h4>备注：</h4>
          <p>{{ selectedTodo.remark }}</p>
        </div>
      </div>
      <div v-else>
        <p>请选择一个任务查看详情</p>
      </div>
    </div>

    <!-- 右侧 - 操作面板 -->
    <div class="column right">
      <h2>操作</h2>
      <div class="action-buttons">
        <el-button type="primary" @click="addRemark">添加备注</el-button>
        <el-button type="primary" @click="prioritize">设置优先级</el-button>
        <el-button type="primary" @click="setDeadline">设置截止时间</el-button>
      </div>
    </div>

    <!-- 优先级选择弹窗 -->
    <dialog ref="priorityDialog">
      <h3>选择优先级</h3>
      <el-button type="primary" @click="setPriority('高')">高</el-button>
      <el-button type="primary" @click="setPriority('中')">中</el-button>
      <el-button type="primary" @click="setPriority('低')">低</el-button>
      <el-button type="primary" @click="closePriorityDialog">取消</el-button>
    </dialog>
  </div>
</template>

<script>
import draggable from "vuedraggable";

export default {
  name: "ResponsiveLayout",
  components: {
    draggable,
  },
  data() {
    return {
      todos: [
        {
          id: 1,
          text: "示例任务",
          completed: false,
          editing: false,
          editValue: "",
          createdAt: new Date(),
          remark: "",
        },
      ],
      newTodo: "",
      filter: "all",
      selectedTodo: null,
    };
  },
  computed: {
    filteredTodos() {
      let filtered = this.todos;
      if (this.filter === "completed") {
        filtered = this.todos.filter((todo) => todo.completed);
      } else if (this.filter === "active") {
        filtered = this.todos.filter((todo) => !todo.completed);
      }
      // 根据优先级排序
      return filtered.sort((a, b) => {
        const priorityOrder = { 高: 1, 中: 2, 低: 3 };
        return priorityOrder[a.priority] - priorityOrder[b.priority];
      });
    },
    // 新增计算属性格式化日期
    formattedCreateDate() {
      if (this.selectedTodo) {
        return new Date(this.selectedTodo.createdAt).toLocaleDateString();
      }
      return "";
    },
    // 新增计算属性格式化截止日期
    formattedDeadline() {
      if (this.selectedTodo && this.selectedTodo.deadline) {
        const date = new Date(this.selectedTodo.deadline);
        return date.toISOString().split("T")[0]; // 标准格式 YYYY-MM-DD
      }
      return "";
    },
  },
  methods: {
    handleTabChange(tab) {
      this.filter = tab;
    },

    addTodo() {
      if (this.newTodo.trim()) {
        this.todos.push({
          id: Date.now(),
          text: this.newTodo.trim(),
          completed: false,
          editing: false,
          editValue: "",
          createdAt: new Date(),
        });
        this.newTodo = "";
      }
    },

    onDragEnd(event) {
      const { oldIndex, newIndex } = event;

      // 如果拖拽前后位置没有变化，则无需处理
      if (oldIndex === newIndex) return;

      // 获取原始 todos 数组中的索引（注意：filteredTodos 是计算属性）
      const oldTodo = this.filteredTodos[oldIndex];
      const newTodo = this.filteredTodos[newIndex];

      // 交换两个 todo 的 priority 值
      const tempPriority = oldTodo.priority;
      oldTodo.priority = newTodo.priority;
      newTodo.priority = tempPriority;
    },

    toggleComplete(todo) {
      todo.completed = !todo.completed;
    },

    removeTodo(id) {
      this.todos = this.todos.filter((todo) => todo.id !== id);
    },

    startEdit(todo) {
      todo.editing = true;
      todo.editValue = todo.text;
    },

    saveEdit(todo) {
      if (todo.editValue.trim()) {
        todo.text = todo.editValue.trim();
        todo.editing = false;
      } else {
        this.removeTodo(todo.id);
      }
    },

    cancelEdit(todo) {
      todo.editing = false;
    },

    addRemark() {
      if (this.selectedTodo) {
        this.selectedTodo.remark =
          prompt("请输入备注内容：", this.selectedTodo.remark || "") || "";
      }
    },

    prioritize() {
      if (this.selectedTodo) {
        this.$refs.priorityDialog.showModal();
      }
    },

    setPriority(priority) {
      if (this.selectedTodo) {
        this.selectedTodo.priority = priority;
        this.closePriorityDialog();
      }
    },
    closePriorityDialog() {
      this.$refs.priorityDialog.close();
    },

    setDeadline() {
      if (this.selectedTodo) {
        const deadline = prompt(
          "设置截止日期（YYYY-MM-DD）：",
          this.selectedTodo.deadline || ""
        );
        if (deadline) {
          this.selectedTodo.deadline = deadline;
        }
      }
    },
    // 新增选择任务方法
    selectTodo(todo) {
      this.selectedTodo = todo;
    },
  },
};
</script>

<style scoped>
.container {
  display: flex;
  flex-wrap: wrap;
  height: 100vh;
  overflow: hidden;
}

.column {
  box-sizing: border-box;
  padding: 20px;
  background-color: #f0f0f0;
  border: 1px solid #ccc;
  text-align: left;
  overflow-y: auto;
}

/* 新增样式 */
.todo-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.todo-list li {
  padding: 10px;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.todo-list li.completed span {
  text-decoration: line-through;
  color: #888;
}

.toolbar {
  margin-bottom: 32px;
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
}

.toolbar input {
  width: calc(100% - 80px);
  padding: 5px;
  margin-right: 10px;
}

.toolbar button {
  width: 70px;
  padding: 5px;
}

.filters {
  margin-bottom: 12px;
}

.filters button {
  margin-right: 10px;
  padding: 5px 10px;
}

.actions button {
  margin-left: 5px;
  padding: 3px 8px;
}

.action-buttons {
  margin-top: 12px;
  display: flex;
  flex-flow: column nowrap;

  button {
    width: 120px;
    margin: 0;
    margin-bottom: 12px;
  }
}

/* 桌面端：三列 */
@media (min-width: 992px) {
  .column.left {
    width: 400px;
  }

  .column.middle {
    flex: 1;
  }

  .column.right {
    width: 300px;
  }
}

/* 平板端：两列 */
@media (min-width: 768px) and (max-width: 991px) {
  .column.left {
    width: 200px;
  }

  .column.middle {
    flex: 1;
  }

  .column.right {
    flex: 0 0 100%;
  }
}

/* 手机端：单列 */
@media (max-width: 767px) {
  .column {
    flex: 0 0 100%;
  }
}
</style>
